package netty.server;


import java.net.InetAddress;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerHandler extends SimpleChannelInboundHandler<byte[]> {
    public static final Logger LOG = LoggerFactory.getLogger(ServerHandler.class);
//    @Override
//    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
//        //get the message
//        System.out.println(ctx.channel().remoteAddress() + " Say : " + msg);
//        //invoke kafka api
//        Server.kafkaClient.sendMessage("a",msg);
//        //response to client "we received it"
//        ctx.writeAndFlush("Received your message !\n");
//    }
@Override
protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
    //get the message
    LOG.info(ctx.channel().remoteAddress() + " Say : " + new String(msg));
    //invoke kafka api
    Server.kafkaClient.sendMessage(Server.kafkaMessageKey,new String(msg));
    //response to client "we received it"
    ctx.writeAndFlush("ok\n");
}
    /*
     *
     *when client connect to server
     * we print client address
     * we response welcome to xx service
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {

        LOG.info("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");

        ctx.writeAndFlush("Welcome to " + InetAddress.getLocalHost().getHostName() + " service!\n");

        super.channelActive(ctx);
    }
}